package api

import (
	"Walker/app/http/model"
	"Walker/app/services"
	"Walker/app/utils"
	data2 "Walker/app/utils/data"
	"Walker/app/utils/response"
	"bufio"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"os"
	"regexp"
	"strings"
)

type Test struct {
	services.TestService
}

//redis 运用string类型的递减函数decr并返回剩余数量具有原子性来实现秒杀
func (s *Test) Oversold(ctx *gin.Context) {
	//并发测试超卖验证
	err := s.TestService.Oversold()
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	response.Success(ctx, "执行成功", "执行成功")
}

//根据redis队列来验证秒杀（list列表）
func (s *Test) OversoldQueue(ctx *gin.Context) {
	//并发测试超卖验证
	err := s.TestService.OversoldQueue()
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	response.Success(ctx, "执行成功", "执行成功")
}

//根据redis队列来验证秒杀（set集合）
func (s *Test) OversoldSQueue(ctx *gin.Context) {
	//并发测试超卖验证
	err := s.TestService.OversoldSQueue()
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	response.Success(ctx, "执行成功", "执行成功")
}

//实现一个人可以买1次可以买m个商品(string+set 去实现)
func (s *Test) OversoldStrQueue(ctx *gin.Context) {
	//并发测试超卖验证
	err := s.TestService.OversoldStrQueue()
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	response.Success(ctx, "执行成功", "执行成功")
}

//雪花算法
func (s *Test) Snowflake(ctx *gin.Context) {
	data, err := utils.NewWorker(23)
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	response.Success(ctx, "执行成功", data.GetId())
}

//testList = append(testList, &Test{Name: "小三"，Age: 12，Sex: true, A: "a", B: "b"， C: "c", D: "d"})
func (s *Test) Test() {
	//测试日志文件
	fmt.Println("33333")
}

//百万数据写入数据库
func (s *Test) Write(ctx *gin.Context) {
	file, err := os.Open("/var/www/html/lr_withome_open_record.sql")
	if err != nil {
		fmt.Println(err.Error())
	}
	fileScanner := bufio.NewScanner(file)
	lineCount := 1
	var re = regexp.MustCompile(`\({1}\d+,{1}`)
	var substitution = "(null,"

	var data []string
	for fileScanner.Scan() {
		//db.Exec(re.ReplaceAllString(fileScanner.Text(), substitution))
		strs := regexp.MustCompile(`\({1}.*\)`)
		params := strs.FindStringSubmatch(fileScanner.Text())
		data = append(data, re.ReplaceAllString(params[0], substitution))
		if lineCount%100000 == 0 {
			fmt.Println(lineCount)
			go handle(data)
			//清空切片
			data = []string{}
		}
		lineCount++
	}
	fmt.Println(lineCount)
	file.Close()
}

//线程处理数据
func handle(data []string) {
	id := rand.Int()
	fmt.Println("当前线程：" + data2.IntToString(id) + "准备开始工作")
	db := model.UseCon()
	str := "INSERT INTO `lr_withome_open_record` VALUES "
	for k, v := range data {
		str = str + v + ","
		if (k+1)%10000 == 0 {
			str = strings.TrimRight(str, ",")
			db.Exec(str)
			str = "INSERT INTO `lr_withome_open_record` VALUES "
		}
	}
	//fileone.Flush()
	fmt.Println("当前线程：" + data2.IntToString(id) + "处理结束")
}
